package com.cbgolf.oa.views;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import butterknife.ButterKnife;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.CalendarAdapter;
import com.cbgolf.oa.adapter.MyBaseAdapter;
import com.cbgolf.oa.adapter.TeeTimeAdapter;
import com.cbgolf.oa.adapter.TeeTimeAdapter.ITeetimeAdapterWaiter;
import com.cbgolf.oa.adapter.recycle.CommonAdapter;
import com.cbgolf.oa.adapter.recycle.ViewHolder;
import com.cbgolf.oa.base.BaseListView;
import com.cbgolf.oa.entity.TeeTimeBean;
import com.cbgolf.oa.entity.TeeTimeBean.TeeTimesBean;
import com.cbgolf.oa.presenter.ITEETIMEPresenter;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.ErrorUtil;
import com.cbgolf.oa.util.ScreenUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.TypeUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.widget.ListViewNew;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xutils.view.annotation.ViewInject;

/**
 * Created by lq on 2018/1/5.
 */

public class TeetimeView extends BaseListView implements OnRefreshListener,
    ITeetimeAdapterWaiter {

  @ViewInject(R.id.topLayout_rl)
  private View topLayout;
  @ViewInject(R.id.topBack_ll)
  private View topBack;
  @ViewInject(R.id.title_tv)
  private TextView titleTv;
  @ViewInject(R.id.title_iv)
  private ImageView titleIv;
  @ViewInject(R.id.title_ll)
  private View titleView;
  @ViewInject(R.id.topRight_tv)
  private TextView topRightTv;
  //
  @ViewInject(R.id.refreshView)
  private SmartRefreshLayout refreshLayout;
  @ViewInject(R.id.recycleView)
  private RecyclerView recyclerView;
  //
  @ViewInject(R.id.calendar_recycleview)
  private RecyclerView calendarRecy;
  @ViewInject(R.id.calendar_ll)
  private View calendar;
  private int year;
  private int month;
  private int day;
  Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      if (null != dialogCalendar) {
        dialogCalendar.dismiss();
      }
      Bundle bundle = msg.getData();
      year = DataUtil.getBundleInt(bundle, "year", 0);
      month = DataUtil.getBundleInt(bundle, "month", 0);
      day = DataUtil.getBundleInt(bundle, "day", 0);
      getData(DateUtil.getDayBegin(year, month, day) + "",
          DateUtil.getDayEnd(year, month, day) + "", codeType);

    }
  };

  private ITEETIMEPresenter worker;

  private TeeTimeAdapter adapter;
  private List<TeeTimesBean> listData = new ArrayList<>();
  private CommonAdapter<TeeTimeBean> calenAdapter;
  private Map<Integer, Boolean> calendarState = new HashMap<>();
  private List<TeeTimeBean> listCalendar = new ArrayList<>();
  private List<String> listCode;
  private ErrorView errorView;
  private PopupWindow pop;

  public TeetimeView(Activity act, ITEETIMEPresenter worker) {
    this.worker = worker;
    ViewUtils.autoInjectAllField(this, act);
    super.init(act);
  }

  @Override
  protected void findViews() {
    errorView = new ErrorView(context);
  }

  @Override
  protected void setViews() {
    titleTv.setText(TextUtil.Text(worker.getActivityTitle()));
    ViewUtils.setText(topRightTv, context.getString(R.string.close_park));
    ViewUtils.setVisible(topRightTv, DataUtil.hasClosePermission());
    setListAdapter();
    year = DateUtil.getNowYear();
    month = DateUtil.getNowMonth();
    day = DateUtil.getDay(new Date());
    ViewUtils.setRefreshCircleHeader(context, refreshLayout);
    refreshLayout.setEnableLoadmore(false);
  }


  private void setListAdapter() {
    adapter = new TeeTimeAdapter(context, this);
    getCalendarData();
    setCalendarAdapter();
    GridLayoutManager gm = new GridLayoutManager(context, 2);
    recyclerView.setLayoutManager(gm);
    recyclerView.setHasFixedSize(true);
    recyclerView.setAdapter(adapter);

  }

  private void getCalendarData() {
    listCalendar.clear();
    TeeTimeBean bean;
    if (selectTime <= 0) {
      selectTime = System.currentTimeMillis();
    }
    for (int i = 0; i < 7; i++) {
      calendarState.put(i, i == 3);
      bean = new TeeTimeBean();
      bean.day =
          DateUtil.getDay(new Date(selectTime + (i - 3) * DateUtil.getOneDay()))
              + "";
      bean.start
          = DateUtil.getDayBegin(selectTime + (i - 3) * DateUtil.getOneDay()) + "";
      bean.end
          = DateUtil.getDayEnd(selectTime + (i - 3) * DateUtil.getOneDay()) + "";
      bean.week = DateUtil.getWeek(selectTime + (i - 3) * DateUtil.getOneDay());
      listCalendar.add(bean);
    }
  }

  private void setCalendarAdapter() {

    calenAdapter = new CommonAdapter<TeeTimeBean>(context, R.layout.item_teetime_calendar,
        listCalendar) {
      @Override
      protected void convert(ViewHolder holder, TeeTimeBean bean, int position) {
        if (null == bean) {
          return;
        }
        holder.setText(R.id.week_tv, TextUtil.Text(bean.week));
        holder.setText(R.id.day_tv, TextUtil.Text(bean.day));
        holder.setBackgroundColor(R.id.layout, ContextCompat.getColor(context,
            DataUtil.getMapBoolean(calendarState, position) ?
                R.color.bg_blue_login : R.color.bg_blue_calendar));
        holder.setTextColor(R.id.week_tv, ContextCompat.getColor(context,
            DataUtil.getMapBoolean(calendarState, position) ?
                R.color.white : R.color.text_blue));
        holder.setOnClickListener(R.id.layout, v -> {
          if (DataUtil.getMapBoolean(calendarState, position)) {
            return;
          }
          for (int i = 0; i < calendarState.size(); i++) {
            calendarState.put(i, (i == position));
          }
          getData(bean.start, bean.end, codeType);
          notifyDataSetChanged();
        });
      }
    };
    GridLayoutManager gm = new GridLayoutManager(context, 7);
    calendarRecy.setLayoutManager(gm);
    calendarRecy.setHasFixedSize(true);
    calendarRecy.setAdapter(calenAdapter);
  }

  private long selectTime = System.currentTimeMillis();

  private void getData(String start, String end, String codeType) {
    if (Util.isNull(start)) {
      selectTime = System.currentTimeMillis();
      worker.getData(null, codeType);
      return;
    }
    if (TypeUtil.parseLong(start) > (DateUtil.getDayEndTime(selectTime).getTime()
        + 3 * DateUtil.getOneDay())
        || TypeUtil.parseLong(end) < (DateUtil.getDayEndTime(selectTime).getTime()
        - 3 * DateUtil.getOneDay())) {
      selectTime = TypeUtil.parseLong(start);
      getCalendarData();
    } else {
      for (int i = 0; i < listCalendar.size(); i++) {
        if (DateUtil.getDay(TypeUtil.parseLong(start))
            == DateUtil.getDay(listCalendar.get(i).start)) {
          calendarState.put(i, true);
          continue;
        }
        calendarState.put(i, false);

      }
    }
    calenAdapter.notifyDataSetChanged();
    worker.getData(start, codeType);
  }

  @Override
  public void showProgress() {
    if (null != refreshLayout && refreshLayout.isRefreshing()) {
      return;
    }
    AnimaUtil.showLoading(context, false);
  }

  @Override
  public void stopProgress() {
    if (null != refreshLayout) {
      refreshLayout.finishRefresh();
    }
    AnimaUtil.stopLoading();
  }

  @Override
  public void getDataFail(String msg) {

    Util.show(msg);
  }

  @Override
  public void getDataSuccess(Object obj) {
    stopProgress();
    TeeTimeBean bean = (TeeTimeBean) obj;
    if (null == bean || Util.listIsNull(bean.teeTimes)) {
      getDataFail(ErrorUtil.NODATA, ErrorUtil.NODATA_CODE);
      return;
    }
    DataUtil.setHasPermission(bean.hasPermission);
//    List<TeeTimeBean> list = (List<TeeTimeBean>) obj;
//    if (Util.listIsNull(list)) {
//      if (Util.listIsNull(listData)) {
//        getDataFail(ErrorUtil.NODATA, ErrorUtil.NODATA_CODE);
//      }
//      return;
//    }
    listData.clear();
    listData.addAll(bean.teeTimes);
    errorView.showData(refreshLayout);
    adapter.setData(listData);
    adapter.notifyDataSetChanged();

  }

  @Override
  public void getDataFail(String msg, int code) {
    stopProgress();
    if (null != errorView) {
      errorView.showError(refreshLayout, msg, code, null);
    }
  }

  @Override
  protected void setListener() {
    refreshLayout.setOnRefreshListener(this);
    topBack.setOnClickListener(v -> worker.back());
    calendar.setOnClickListener(v -> showCalendar());
    titleView.setOnClickListener(v -> {
      if (Util.listIsNull(listCode) || listCode.size() == 1) {
        return;
      }
      showCodeTypePop();
    });
    ViewUtils.setClick(topRightTv, v -> worker.showCloseParkList());
  }


  private void showCodeTypePop() {
    if (null != pop && pop.isShowing()) {
      pop.dismiss();
      pop = null;
      return;
    }
    titleIv.setImageResource(R.mipmap.teetime_arrowdown);
    pop = new PopupWindow(context);
    View view = context.getLayoutInflater().inflate(R.layout.pop_codetype, null);
    ListViewNew listView = ButterKnife.findById(view, R.id.listView);
    List<String> list = new ArrayList<>();
    for (int i = 0; i < listCode.size(); i++) {
      if (!Util.isEquals(listCode.get(i), codeType)) {
        list.add(listCode.get(i));
      }
    }
    MyBaseAdapter<String> adapter = new MyBaseAdapter<String>(R.layout.pop_codetype,
        context, list) {
      @Override
      public View getView(int position, View view, ViewGroup parent, String code) {
        if (Util.isNull(code)) {
          return view;
        }
        setVisible(R.id.listView, false);
        setVisible(R.id.tv, true);
        setText(R.id.tv, "Teetime-" + code.substring(0, 1) + "半场");
        view.findViewById(R.id.tv).setOnClickListener(v -> {
          pop.dismiss();
          titleTv.setText("Teetime-" + code.substring(0, 1) + "半场");
          codeType = code;
          getData(null, null, codeType);
        });
        return view;
      }
    };
    listView.setAdapter(adapter);
    LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams) listView.getLayoutParams();
    ll.width = ScreenUtil.getWidth();
    ll.height = ViewGroup.LayoutParams.WRAP_CONTENT;
    listView.setLayoutParams(ll);
    AutoUtil.auto(view);
    pop.setContentView(view);
    pop.setWidth(ScreenUtil.getWidth());
    pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    pop.setOutsideTouchable(true);
    pop.setTouchable(true);
    pop.setFocusable(true);
    pop.setBackgroundDrawable(new ColorDrawable(0x00000000));
    pop.showAsDropDown(topLayout);
    pop.setOnDismissListener(() -> titleIv.setImageResource(R.mipmap.teetime_arrowup));

  }

  private Dialog dialogCalendar;
  private int tempYear;
  private int tempMonth;

  private void showCalendar() {
    dialogCalendar = new Dialog(context, R.style.mDialog);
    View view = context.getLayoutInflater().inflate(R.layout.dialog_calendar_phone, null);
    View before = view.findViewById(R.id.dialog_calendar_before_ll);
    View after = view.findViewById(R.id.dialog_calendar_after_ll);
    TextView title = (TextView) view.findViewById(R.id.dialog_calendar_title_tv);
    GridView gridView = (GridView) view.findViewById(R.id.dialog_calendar_gridview);
    AutoUtil.auto(view);
    dialogCalendar.setContentView(view);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    tempYear = year;
    tempMonth = month;
    title.setText(year + "年    " + month + "月");
    final CalendarAdapter adapterCalendar = new CalendarAdapter(context, year, month, day, handler);
    gridView.setAdapter(adapterCalendar);
    after.setOnClickListener(v -> {
      tempMonth = tempMonth + 1;
      if (tempMonth > 12) {
        tempMonth = 1;
        tempYear += 1;
      }
      title.setText(tempMonth + "月 " + tempYear + "年");
      adapterCalendar.clear();
      adapterCalendar.setData(tempYear, tempMonth);
      adapterCalendar.upDataUI();
    });
    before.setOnClickListener(v -> {
      tempMonth = tempMonth - 1;
      if (tempMonth == 0) {
        tempMonth = 12;
        tempYear = tempYear - 1;
      }
      title.setText(tempMonth + "月 " + tempYear + "年");
      adapterCalendar.clear();
      adapterCalendar.setData(tempYear, tempMonth);
      adapterCalendar.upDataUI();
    });

    dialogCalendar.show();
  }

  @Override
  public void refershFail(String msg, int code) {

  }

  @Override
  public void refershSuccess(Object obj) {

  }

  @Override
  public void loadMoreFail(String msg, int code) {

  }

  @Override
  public void loadMoreSuccess(Object obj) {

  }

  @Override
  public void onRefresh(RefreshLayout refreshlayout) {
    worker.refresh();
  }


  private String codeType;

  public void getCodeTypeSuccess(Object obj) {
    listCode = (List<String>) obj;
    codeType = listCode.get(0);
    if (!Util.isNull(codeType)) {
      titleTv.setText("Teetime-" + codeType.substring(0, 1) + "半场");
    }
    titleIv.setVisibility(View.VISIBLE);
    titleIv.setImageResource(R.mipmap.teetime_arrowup);
  }

  public void getCodeTypeFail(String msg, int code) {
    getDataFail(msg, code);
  }



  @Override
  public void addPerson(TeeTimesBean bean) {
    worker.addPerson(bean);
  }

  @Override
  public void reducePerson(TeeTimesBean bean) {
    worker.reducePerson(bean);
  }
}
